package com.woniuxy.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.commons.exception.LateException;
import com.woniuxy.commons.utile.BeanCopyUtil;
import com.woniuxy.commons.utile.Result;
import com.woniuxy.controller.dto.MyonerepairDto;
import com.woniuxy.controller.dto.AccountDto;
import com.woniuxy.controller.dto.PageRepairInfoDto;
import com.woniuxy.controller.dto.myrepairDto;
import com.woniuxy.controller.form.*;
import com.woniuxy.dao.*;
import com.woniuxy.dao.info.myrepairInfo;
import com.woniuxy.dao.model.Account;
import com.woniuxy.dao.model.RepairInfo;
import com.woniuxy.dao.model.RepairProject;
import com.woniuxy.service.RepairAttachmentService;
import com.woniuxy.service.RepairInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.service.RepairLogService;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.jdbc.Null;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.Console;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * <p>
 * 维修表 服务实现类
 * </p>
 *
 * @author Keep it simple
 * @since 2022-06-28
 */
@Service
public class RepairInfoServiceImpl extends ServiceImpl<RepairInfoDao, RepairInfo> implements RepairInfoService {


    @Resource
    private RepairInfoDao repairInfoDao;

    @Resource
    private RepairProjectDao repairProjectDao;

    @Resource
    private RepairAreaDao repairAreaDao;

    @Resource
    private RepairUnitDao repairUnitDao;

    @Resource
    private AccountDao accountDao;

    @Resource
    private RepairInfoService repairInfoService;

    @Resource
    private RepairAttachmentService repairAttachmentService;

    @Override
    //添加维修信息
    public Integer addRepariInfo(RepairuserForm repairuserForm) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
//        if (repairuserForm.getAccount()==null)throw new LateException(1101,"账号不能为空");
        if (repairuserForm.getRepairusername()==null) throw new LateException(1101,"维修人不能为空");
        if (repairuserForm.getUserphone()==null)throw new LateException(1101,"电话不能为空");
        if (repairuserForm.getRepairarea()==null)throw new LateException(1101,"维修区域不能为空");
        if (repairuserForm.getRepairtype()==null)throw new LateException(1101,"维修项目不能为空");
        if (repairuserForm.getOrderrepairdate()==null)throw new LateException(1101,"预约时间不能为空");
        if (repairuserForm.getRepaircontent()==null)throw new LateException(1101,"故障原因不能为空");
        if (repairuserForm.getDetaillocation()==null)throw new LateException(1101,"详细地址不能为空");
        if (repairuserForm.getOssurl()==null)throw new LateException(1101,"上传图片不能为空");
        RepairInfo repairInfo = BeanCopyUtil.copyOne(repairuserForm, RepairInfo.class);
        repairInfo.setRepairnum(sb.toString());
        repairInfo.setRepairstate(1);//1：报修 2：审核 3 ：派工 4：决算 5 完工
        AccountDto principal = (AccountDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userId =principal.getId();
        repairInfo.setRepairuser(userId);
        int insert = repairInfoDao.insert(repairInfo);
        //附件表添加一条关于repairNum和ossurl的信息
        repairAttachmentService.addRepairArrachment(sb.toString(), repairuserForm.getOssurl());
        return insert;
    }

    @Override
    public myrepairDto personaluser(studentForm studentForm) {
        Page<myrepairInfo> myrepairInfoPage = new Page<>(studentForm.getPage(), 10);
        IPage<myrepairInfo> personaluser = repairInfoDao.personaluser(myrepairInfoPage, studentForm.getStudentid());
        List<myrepairInfo> records = personaluser.getRecords();//得到当前页数据
        long pages = personaluser.getPages();//获取一共多少页
        myrepairDto myrepairDto = new myrepairDto();
        myrepairDto.setNum(pages);
        myrepairDto.setP(records);
        return myrepairDto;
    }

    @Override
    public MyonerepairDto showrepair(ShowrepairForm showrepairForm) {
        MyonerepairDto showmyrepair = repairInfoDao.showmyrepair(showrepairForm);
        AccountDto principal = (AccountDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        showmyrepair.setUsername(principal.getUsername());
//        showmyrepair.setUserPhone(principal.getAccountPhone());
        if (showrepairForm==null){
            throw new LateException(1003,"个人维修详情错误");
        }
        return showmyrepair;
    }

    /**
     * 查询维修信息分页
     * @param pageRepairInfoForm
     * @return PageRepairInfoDto
     */
    @Override
    public PageRepairInfoDto getRepairInfo(PageRepairInfoForm pageRepairInfoForm) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //未登录无法访问该资源，不需要判断空
        AccountDto principal = (AccountDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userRole = principal.getState();
        Integer userId = principal.getId();
        System.out.println(principal);
        QueryWrapper<RepairInfo> myQW = new QueryWrapper<RepairInfo>();
        if (pageRepairInfoForm.getRepairState()!=null &&pageRepairInfoForm.getRepairState()!=0) myQW.eq("repairState",pageRepairInfoForm.getRepairState());
        if (pageRepairInfoForm.getRepairType()!=null &&pageRepairInfoForm.getRepairType()!=0) myQW.eq("repairType",pageRepairInfoForm.getRepairType());
        if (pageRepairInfoForm.getRepairUnit()!=null &&pageRepairInfoForm.getRepairUnit()!=0) myQW.eq("repairProject_Id",pageRepairInfoForm.getRepairUnit());
        if (pageRepairInfoForm.getRepairArea()!=null &&pageRepairInfoForm.getRepairArea()!=0) myQW.eq("repairArea",pageRepairInfoForm.getRepairArea());
        //这里用上下文获取,根据登录用户角色，
//        if (pageRepairInfoForm.getRepairPersonId()!=null) myQW.eq("repairPersonId",pageRepairInfoForm.getRepairPersonId());
//        if (pageRepairInfoForm.getRepairUserId()!=null) myQW.eq("repairUserId",pageRepairInfoForm.getRepairUserId());
        //state 0管理员 不做处理查询全部
        // pass
        System.out.println("****"+userRole+"**********");
        //state 1维修人员 维修工-维修工自身全部
        myQW.eq(userRole==1,"repairPersonId",userId);
        //state 2返回对应数据学生-学生自身全部
        System.out.println(userRole);
        myQW.eq(userRole==2,"repairUser",userId);
        if (pageRepairInfoForm.getContentLike()!=null ||pageRepairInfoForm.getNmsl()!=null ) myQW.and(
                i->i.like(pageRepairInfoForm.getContentLike()!=null,"repairContent",pageRepairInfoForm.getContentLike()).or()
                .like(pageRepairInfoForm.getNmsl()!=null,"repairUserName",pageRepairInfoForm.getNmsl()).or()
                .like(pageRepairInfoForm.getNmsl()!=null,"userPhone",pageRepairInfoForm.getNmsl())
        );
        if(pageRepairInfoForm.getDateInterval()!=null && pageRepairInfoForm.getDateInterval().size()!=0) myQW.and(
                i->i.gt("repairDate", LocalDateTime.parse(pageRepairInfoForm.getDateInterval().get(0),df))
                .lt("repairDate", LocalDateTime.parse(pageRepairInfoForm.getDateInterval().get(1),df))
        );
        myQW.orderByDesc("repairDate");
        PageRepairInfoForm repairType = repairInfoService.page(pageRepairInfoForm,myQW);
        PageRepairInfoDto pageRepairInfoDto = BeanCopyUtil.copyOne(repairType,PageRepairInfoDto.class);
        return pageRepairInfoDto;
    }

    /**
     * 获取维修工人维修的所有信息
     * @param
     * @return
     */
    @Override
    public Page<RepairForm> showWorkerRepair(Integer pageNum, Integer pageSize) {
        //判断页数，条数
        Integer pageNumValue = pageNum == null ? 1: pageNum;
        Integer pageSizeValue = pageSize == null ? 10: pageSize;

        //通过上下文获取该账号的id
        AccountDto AccountDto = (AccountDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer id = AccountDto.getId();

        //分页
        QueryWrapper<RepairInfo> wrapper = new QueryWrapper<RepairInfo>();
        wrapper.eq("repairPersonId", id);
        wrapper.orderByDesc("repairDate");//降序
        Page<RepairInfo> page = repairInfoDao.selectPage(new Page<RepairInfo>(pageNumValue, pageSizeValue), wrapper);

        Page<RepairForm> repairFormPage = new Page<>();
        repairFormPage.setPages(page.getPages());
        repairFormPage.setTotal(page.getTotal());
        repairFormPage.setSize(page.getSize());
        repairFormPage.setCurrent(page.getCurrent());
        List<RepairForm> list = new ArrayList<>();

        List<RepairInfo> records = page.getRecords();
        for (RepairInfo record : records) {
            System.out.println(record);
            RepairForm repairForm = new RepairForm();
            repairForm.setRepairnum(record.getRepairnum());
            repairForm.setRepaircontent(record.getRepaircontent());
            repairForm.setRepairdate(record.getRepairdate());
            repairForm.setResponsetime(record.getResponsetime());
            repairForm.setRepairstate(record.getRepairstate());
            repairForm.setRepairtype(repairProjectDao.selectById(record.getRepairtype()).getProjectName());
            repairForm.setRepairarea(repairAreaDao.selectById(record.getRepairtype()).getAreaName());
            repairForm.setServicecompany(repairUnitDao.selectById(record.getServicecompany()).getUnitName());
            repairForm.setAcceptuser(accountDao.selectById(record.getAcceptuser()).getAccountName());
            list.add(repairForm);
        }
        repairFormPage.setRecords(list);
        return repairFormPage;
    }

}

